import {app} from "electron";
import {join} from 'node:path'
import {appendFile, existsSync, mkdirSync} from 'node:fs'

import moment from 'moment'

const LowNodePromis = import('lowdb/node')
const LowPromis = import('lowdb')

const defVal = {
  winOpt: {
    size: {
      width: 900,
      height: 670
    }
  },
  option: {
    copies: 1,
    monochrome: false,
    orientation: 'portrait',
    paperSize: "A5",
    scale: "fit",
    side: "simplex",
  },
  printCount: 0,
}
let db;

async function initDb() {
  const dir = join(app.getPath("userData"), 'data')
  if (!existsSync(dir)) {
    mkdirSync(dir)
  }
  await Promise.all([LowPromis, LowNodePromis]).then(([lowdb, node]) => {
    const adapter = new node.JSONFileSync(join(dir, 'db.json')); // 指定数据文件
    db = new lowdb.LowSync(adapter, defVal);
  })
  db.read()
}


const log = {
  addLog(str: string) {
    const dir = app.getPath("logs")
    if (!existsSync(dir)) {
      mkdirSync(dir)
    }
    const logFile = join(dir, `log-${moment().format('YYYY-MM-DD')}.log`)

    appendFile(logFile, `${moment().format('YYYY-MM-DD HH:mm:ss')}\t${str}\n`, 'utf8', (err) => {
      if (err) {
        console.log("日志写入错误", err)
      }
    })
  },
  getLog() {

  }
};

export {db, initDb, log}
